// KULoket Printer 
// Resource: content-script.js
// Version: 1.0
// Author: Pieter Laenen

/* 
	This script will be injected into the KULoket webpage.
	The script localizes the frame containing the embedded KULoket information, 
		injects a printer-friendly css file and adds a print button.
 */

/**main procedure*/

//build index list
var indexes = ['ivuFrm_page0ivu4','isolatedWorkArea'];
//get iframe
var iframe = accessIFrames(document, indexes);
//continue on page load
iframe.onload = dynamicFrameBuild; 

/**end of main procedure*/

/**
 * Migrates down the stack of embedded iframes, and locates the next level by searching for the given 
 *	 index in the array.
 *	
 *	@param index An array of indexes containing the indexes (integer), 
 *				id's (string) or names (string) of the iframes on each level.
 *	@return The HTMLIFrameElement index.length levels deep in the given document.
 *				Null if given index is null or not an array.
 */
function accessIFrames(doc, index){
	console.log('Starting access loop');

	if(index == null){
		console.log('index: '+ index);
		return null;
	}

	//for every index in the list, find the iframe embedded in the current level iframe.
	for(var i = 0; i < index.length; i++){
		console.log('Level '+ i);
		//on first call, get iframe from document
		if(i==0){
			iframe = accessDocument(document, index[i]);
		}
		else{
			iframe = accessIFrame(iframe, index[i]);
		}

		//if result is null, abort loop
		if(iframe == null){
			console.log('Break loop: frame is null');
			break;
		}
		console.log('result: '+ iframe + " " +iframe.name + " " + iframe.id);
	}

	console.log('Loop end; Returning: ' + iframe);

	return iframe;
}

/**
	Get the iframe embedded in the given iframe with the given index.
	Get the contentDocument of the iframe and calls searches the document for iframes with the 
	given index.
	@param index The index (integer), id (string) or name (string) of the resulting iframe.
	@return The iframe with the given index.
 */
function accessIFrame(iframe, index){
	console.log('frame: ' + iframe + " " +iframe.name + " " + iframe.id);

	//get frame document
	var frameDoc = iframe.contentDocument;

	//access document for embedded frames
	var result = accessDocument(frameDoc, index);

	return result;	
}

/**
	Get the iframe embedded in the given document with the given index.
	@param index The index (integer), id (string) or name (string) of the resulting iframe.
	@return the iframe with the given index.
 */
function accessDocument(doc, index){
	console.log('document: '+ doc);
	console.log('index: ' + index);

	//get iframes
	var embeddedFrames = doc.getElementsByTagName('iframe');
	console.log('embedded frames: ' + embeddedFrames.length);

	//get iframe at given index
	var result = embeddedFrames[index];	

	return result;
}

/**
 * Make the iframe KULPrinter compatible
 */
function dynamicFrameBuild(){
	console.log('IFrame is loaded');
	//disable icon
	sendForPageAction(false);
	//inspect url and get page marker
	page = checkURL(iframe);
	//retrieve css url and add file to frame
	sendForCSSFile(page);
	//add button in right place
	sendForIcon();
	//check for print overwrite
	if(iframe.contentDocument.getElementById('resultaten') != null){
		//retrieve print function script
		sendForScript();
	}

	if(page != null){
		sendForPageAction(true);
	}
}

/**
 * Checks the iframe's url for known regexes.
 * @param iframe An iframe with a contentDocument.
 * @returns A string marker for the file referenced in the iframe's URL.
 */
function checkURL(iframe){
	var url = iframe.contentDocument.URL;

	var regex;
	var result;

	//supported regexes
	regex = /main_toleranties/;
	if(regex.test(url))
		result = "studievoortgang";
	console.log("IFrame url page reference: " + result);
	return result;
}

/**
 * Ask the extension for the full url of the CSS file referenced by the page name and adds the css link
 * to the iframe (global variable).
 * @param page A string marker for the css file.
 */
function sendForCSSFile(page){
	console.log("Requesting css file for marker " + page);
	chrome.extension.sendRequest({page: page},addStylesheet);	
}

/**
 * Add the given css file url as link in the iframe (global variable).
 */
function addStylesheet(cssurl){

	console.log("Injecting css: " +cssurl);

	var element = document.createElement('link');

	element.rel= "stylesheet"; 
	element.type= "text/css";
	element.href = cssurl;
	element.media = "print";

	iframe.contentDocument.getElementsByTagName('head').item(0).appendChild(element);
}

function sendForScript(){
	console.log("Requesting javascript file for window.print() override");
	chrome.extension.sendRequest({override:true}, addScript);
}

/**
 * Add the given script file url as script element in the 'mainform'.
 */
function addScript(scripturl){
	console.log("Injecting script: " +scripturl);

	var element = document.createElement('script');

	element.src = scripturl;

	iframe.contentDocument.getElementById('mainform').appendChild(element);
}

function sendForIcon(){
	console.log("Requesting kulprinter icon");
	chrome.extension.sendRequest({icon: true}, addButton);
}

/**
 * Add the button in a proper, visible place
 * @param iframe
 * @param page
 */
function addButton(iconurl){

	console.log("Add button to page with marker " + page);

	var button = createButton(iconurl);

	//location
	if(page = "studievoortgang"){
		var keuzecel = iframe.contentDocument.body.getElementsByClassName('keuzecel').item(0);
		keuzecel.rows[0].cells[1].appendChild(button);
	}
}

/**
 * Format a print button with kulprinter icon.
 * @returns a link ('a') tag for printing
 */
function createButton(iconurl){
	var link = document.createElement('a');
	link.href = "javascript:window.print()";
	link.id = "print";
	link.style.textDecoration = "none";
	link.style.color = "inherit";

	var img = document.createElement('img');
	img.src = iconurl;
	img.style.margin = "0 2px";
	var text = document.createElement('span');
	text.innerHTML = "Print";
	text.style.margin = "0 2px";

	link.appendChild(img);
	link.appendChild(text);

	return link;
}

function sendForPageAction(status){
	chrome.extension.sendRequest({pageIcon: status});
}